import {fetch} from '../../../utils/axios'
import {getFormatData} from '../../../utils/common'

const state = {
  name: 'Salt临时表',
  search: '',
  dialog: false,
  viewSalt: {minion_id: '', grains: ''},
  totalItems: 0,
  items: [],
  loading: true,
  pagination: {},
  opration: '',
  headers: [],
  etext: 'No Data',
  rowsPerPageItems: [10, 50, 100, { text: 'All', value: 100000 }],
  searchLabel: 'name',
  editedIndex: -1
}

const mutations = {
  handlerSalt (state) {
    state.loading = true
    const { sortBy, descending, page, rowsPerPage } = state.pagination
    let ordering = descending ? '-' + sortBy : sortBy
    fetch('/salt/', {
      offset: (page - 1) * rowsPerPage,
      limit: rowsPerPage,
      ordering,
      search: state.search
    }).then((response) => {
      state.items = response.results
      state.totalItems = response.count
      state.loading = false
    }).catch((error) => {
      state.etext = error.response
    })
  },
  loadSaltHeaders (state) {
    fetch('/getmodels/', {
      appname: 'salt',
      modelname: 'Salt_grains'
    }).then((response) => {
      state.headers = JSON.parse(response)
    }).catch((error) => {
      state.etext = error.response
    })
  },
  openSaltView (state, payload) {
    let url = '/salt/' + payload + '/'
    fetch(url, {
    }).then((response) => {
      state.viewSalt.minion_id = response['minion_id']
      state.viewSalt.grains = getFormatData(response['grains'])
    }).catch((error) => {
      alert(error.response)
    })
    state.dialog = true
  }
}

const actions = {
  handlerSalt ({commit}) {
    commit('handlerSalt')
  },
  loadSaltHeaders ({commit}) {
    commit('loadSaltHeaders')
  },
  openSaltView ({commit}, payload) {
    commit('openSaltView', payload)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
